package com.googlecode.dgwt.client.dijit.form;

import com.googlecode.dgwt.client.dijit.Dijit;
import com.googlecode.dgwt.client.dijit.form.base.TextBoxBase;
import com.googlecode.dgwt.client.dijit.theme.CSS;
import com.googlecode.dgwt.client.dojo.Dojo;
import com.googlecode.dgwt.client.dojo.string.CharCase;

/**
 * @author wellsantos@wellsantos.com
 * @since 0.01
 */
public class TextBox extends TextBoxBase {


    protected boolean autoTrim = true;
    protected CharCase charCase = null;
    

    public TextBox() {
        super(true);
    }

    
    protected TextBox(boolean ready) {
        super(ready);
    }


    @Override
    protected String unformat(String text) {
        if (autoTrim) {
            text = text.trim();
        }
        return super.unformat(text);
    }


    @Override
    protected void onChanging(String lastValue) {
        super.onChanging(lastValue);
        String oldValue = getValue();
        String value = oldValue;
        
        if (charCase == CharCase.LOWER_CASE) {
            value = value.toLowerCase();
        }
        else if (charCase == CharCase.UPPER_CASE) {
            value = value.toUpperCase();
        }
        else if (charCase == CharCase.PROPER_CASE) {
            value = Dojo.string.toProperCase(value);
        }
        else {
            return;
        }
        
        if (!value.equals(oldValue)) {
            int pos = getCursorPos();
            int len = getSelectionLength();
            setValue(value, false);
            setSelectionRange(pos, len);
        }        
    }


    @Override
    public CSS getThemeCSS() {
        return Dijit.getTheme().dijitTextBox();
    }

    
    @Override
    protected void buildRendering() {
        loadFromTemplate(Dijit.TEMPLATE_RESOURCES.textBox());
    }
    

    public void setAutoTrim(boolean autoTrim) {
        this.autoTrim = autoTrim;
    }

    
    public boolean isAutoTrim() {
        return autoTrim;
    }

    
    public void setCharCase(CharCase charCase) {
        if (this.charCase != charCase) {
            this.charCase = charCase;
            this.onChanging(lastChangingValue);
        }
    }

    
    public CharCase getCharCase() {
        return charCase;
    }    
    
}
